﻿using BaseUtils.Helper;
using BaseUtils.Utils;
using NW_WEB_Service.com.app.entities.vo;
using Service.src.com.utils.modal;
using Service.src.Flow.Server;
using Service.src.Model.Folw;
using Service.src.NW.Model;
using Service.src.NW.Model.Folw;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace NW_WEB_Service.App.Controllers
{
    [RoutePrefix("api/flow")]
    public class FlowController : ApiController
    {
        /// <summary>
        /// 根据流程ID， 执行流程
        /// </summary>
        /// <param name="FlowId"></param>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [Route("run/{FlowId:int}")]
        public void RunFlow(long FlowId)
        {
            if (FlowId <= 0)
            {
                throw new Exception("流程ID错误，请检测流程");
            }
            FlowServer.RunFlow(FlowId);
        }

        /// <summary>
        /// 停止某个流程
        /// </summary>
        /// <param name="FlowId"></param>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [Route("stop/{FlowId:int}")]
        public HttpResult StopFlow(int FlowId)
        {
            if (FlowId <= 0)
            {
                throw new Exception("流程ID错误，请检测流程");
            }
            bool IsStop = FlowServer.StopFlow(FlowId);
            return new HttpResult().Success(IsStop);
        }

        [HttpGet]
        [Route("list")]
        public HttpResult GetFlowList()
        {
            HttpResult Result = new HttpResult();
            List<FlowBaseInfo> flows = new List<FlowBaseInfo>();
            string Flows = AppData.AppPath + AppData.RuntimeFlowData + AppData.AllFlowFileName;
            if (!System.IO.File.Exists(Flows))
            {
                Result.Message = "未找到流程文件";
            }
            else
            {
                string nws = FileHelper.ReadContent(Flows);
                flows = ConvertHelper.ToObject<List<FlowBaseInfo>>(nws);
                AppData.SetAllFlows(flows);
            }

            return Result.Success(flows);
        }

        [HttpGet]
        [Route("{FlowId:int}")]
        public HttpResult Get(int FlowId)
        {
            if (FlowId <= 0)
            {
                throw new Exception("流程ID错误，请检测流程");
            }
            FlowRoot Flow = FlowProcessor.GetFlow(FlowId);

            string zip = Flow.ToJson(new[] { "Children" });
            FlowRoot nf = ConvertHelper.ToObject<FlowRoot>(zip);
            return new HttpResult().Success(zip);
        }

        /// <summary>
        /// 获取所有节点的详细信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("all-flow-node-detail")]
        public HttpResult GetAllFlowNodeDetail()
        {
            string AllFlowNodeDetail = AppData.OpenFlows.Values.ToJson();
            return new HttpResult().Success(AllFlowNodeDetail);
        }

        /// <summary>
        /// 更新节点
        /// </summary>
        /// <param name="NodeItemJson"></param>
        /// <param name="GroupJson"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("update-node")]
        public string UpdateFlowNode([FromBody] UpdateFlowVO UpdateFlow)
        {
            FlowServer flowServer = new FlowServer();
            return flowServer.UpdateFlowNode(UpdateFlow.FlowId, UpdateFlow.NodeItemJson);
        }



        /// <summary>
        /// 删除流程
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("{Id:int}")]
        public HttpResult DeleteFlow(int Id)
        {
            //List<FlowBaseInfo> nws = AppData.AllFlowBaseInfos.Where(s => s.id != Id).ToList();
            FlowBaseInfo RemoveFlow;
            AppData.AllFlowBaseInfos.TryRemove(Id, out RemoveFlow);
            List<FlowBaseInfo> nws = AppData.AllFlowBaseInfos.Values.ToList();
            FileHelper.WriteContent($"{AppData.AppPath + AppData.RuntimeFlowData}", AppData.AllFlowFileName, nws.ToJson());
            return GetFlowList();
        }

        /// <summary>
        /// 添加流程
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public HttpResult Save()
        {
            List<FlowBaseInfo> nws = AppData.AllFlowBaseInfos.Values.ToList();
            FlowBaseInfo Item = nws.OrderByDescending(s => s.id).FirstOrDefault() ?? new FlowBaseInfo();
            long Index = Item.id + 1;
            string Path = "NEW_" + Index;
            FlowBaseInfo _new = new FlowBaseInfo();
            _new.id = Index;
            _new.Title = Path;
            _new.FileName = "index.nw";
            _new.FilePath = AppData.RuntimeFlowDataFlowDirectory + Path;
            _new.OutTime = 10000;

            AppData.AllFlowBaseInfos.TryAdd(_new.id, _new);

            FileHelper.WriteContent($"{AppData.AppPath+AppData.RuntimeFlowData}", AppData.AllFlowFileName, AppData.AllFlowBaseInfos.Values.ToList().ToJson());
            FlowRoot Folw = new FlowRoot();
            Folw.name = _new.Title;
            Folw.Id = _new.id;
            FlowProcessor.UpdateFlow(Folw, false);
            new FlowController().GetFlowList();
            AppData.AddOpenFlow(Folw);
            return new HttpResult().Success(_new);
        }

        /// <summary>
        /// 更新流程名称
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Title"></param>
        /// <returns></returns>
        //public string UpdateFlow(int id, string Title)
        [HttpPut]
        [Route ("update-flow")]
        public HttpResult UpdateFlow([FromBody] FlowBaseInfo NewFlowInfo)
        {
            FlowBaseInfo Old = AppData.AllFlowBaseInfos[NewFlowInfo.id] ?? new FlowBaseInfo();
            Old.Title = NewFlowInfo.Title;
            Old.EnableCycle = NewFlowInfo.EnableCycle;
            Old.CycleTime = NewFlowInfo.CycleTime;
            Old.OutTime = NewFlowInfo.OutTime;

            string FlowJson = AppData.AllFlowBaseInfos.Values.ToList().ToJson();
            FileHelper.WriteContent($"{AppData.AppPath + AppData.RuntimeFlowData}", AppData.AllFlowFileName, FlowJson);
            return new HttpResult().Success(FlowJson);
        }


    }
}
